import cv2
import numpy as np
from press_image import process_image_with_morphology, laplacian_sharpen
from dynamic import get_hsv_from_file
image = cv2.imread("images/color_recognition/rect4.jpg")
height, width = image.shape[:2]
image = image[5:height-10, 5:width-10]
# image = cv2.resize(image, None, fx=0.3, fy=0.3, interpolation=cv2.INTER_LINEAR)
image = cv2.GaussianBlur(image, (3, 3), 0)
# image = laplacian_sharpen(image)
# gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# # kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
# # gray = cv2.dilate(gray, kernel)
# gray = process_image_with_morphology(image)
# hsv_list = get_hsv_from_file('hsv_record2.pkl')
# mask = cv2.inRange(image, hsv_list[0][0], hsv_list[0][1])
# cv2.imshow('mask', mask)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

canny = cv2.Canny(gray, 30, 90)
cv2.imshow('canny', canny)
# cv2.waitKey(0)
# 膨胀操作
kernel_dilation = np.ones((3, 3), np.uint8)
dilated = cv2.dilate(gray, kernel_dilation, iterations=2)

contours, hierarchy = cv2.findContours(canny, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
print(f"hierarchy:{hierarchy}")
for c in contours:
    peri = cv2.arcLength(c, True)
    edge_count = len(cv2.approxPolyDP(c, 0.02*peri, True))
    print(edge_count)
    if edge_count > 2:
        x, y, w, h = cv2.boundingRect(c)
        x = x-5
        y = y-5
        w = w + 10
        h = h + 10
        cv2.rectangle(image, (x, y), (x+w, y+h), (255, 0, 0), 2)
        #  triangle,quadrangle,pentagon,hexagon,circle
        cv2.putText(image, f"{edge_count}", (x+w+5, y), cv2.FONT_HERSHEY_SCRIPT_SIMPLEX, 1, (0, 0, 255), 1)
cv2.imshow('gray', gray)
#cv2.imshow("canny", canny)
cv2.imshow("new_image", image)
cv2.waitKey(0)

